<?php

/* 
 *  author : ahfee
 *  date : 2016-3-22.
 *  explain:调用微信公众号接口
 */

class WeixinapiController extends \Core_BackendCtl {
    
    
    public function indexAction(){

    }
    
    /**
     * 获取access_token
     * @param type $appid  公众号id
     * @param type $secret 密钥
     */
    public function  GetTokenAction($appid,$secret){
        $pdata = $this->getAllPost();
        $check  = array();
        
        if(!$pdata['appid'] && $pdata['act']==1){
            $check['appid'] = "appid不能为空！";
        }
        if(!$pdata['secret'] && $pdata['act']==1 ){
            $check['secret'] = "secret不能为空！";
        }
        
        $message = array();
        if(empty($check) && $pdata['act']==1){
            $apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$pdata['appid']."&secret=".$pdata['secret'];         
            $result = $this->weixinCurlGet($apiUrl);
            $result = json_decode($result,true);
            
            if($result['access_token']){
                tools_help::setCookie('accese_token',$result['access_token'],7200);
                $this->_view->assign('Message',"  access_token: ".$result['access_token']."  保存时间：".$result['expires_in']."秒 ");
            }else{
                $this->_view->assign('ErrorMessageStop'," errcode: '".$result['errcode']."'   errmsg: '".$result['errmsg']."' ");
            }

        }else{
            $errormsg = "";
            foreach($check as $v){
                $errormsg.= $v." ";
            }
            $this->_view->assign('ErrorMessage',$errormsg);
            $this->_view->assign("errors", $check);
        }
       
    }    
    
    /**
     * 自定义菜单
     * @param type $type
     * @param type $token
     * @param type $body
     */
    public function MenuAction($type,$token,$body){
        $pdata = $this->getAllPost();
        $check  = array();
        if(!$pdata['type']  && $pdata['act']==1){
            $check['type'] = "接口类型不能为空！";
        }
        if(!$pdata['token'] && $pdata['act']==1){
            $check['token'] = "token不能为空！";
        }
        if(!$pdata['body'] && $pdata['act']==1){
            $check['body'] = "body不能为空！";
        }
        //print_r($check);exit;
        $message = array();
        if(empty($check) && $pdata['act']==1){
            $apiUrl = " https://api.weixin.qq.com/cgi-bin".$pdata['type']."?access_token=".$pdata['token'];   
            //$apiUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token".$pdata['token'];
            //echo $apiUrl;exit;
            $result = $this->weixinCurlPost($apiUrl);
           //$result = tools_help::getpost($apiUrl, $arr);
            var_dump($result);exit;
            $result = json_decode($result,true);
            print_R($pdata['body']);exit;
            if($result['access_token']){
                tools_help::setCookie('accese_token',$result['access_token'],7200);
                $this->_view->assign('Message',"  access_token: ".$result['access_token']."  保存时间：".$result['expires_in']."秒 ");
            }else{
                $this->_view->assign('ErrorMessageStop'," errcode: '".$result['errcode']."'   errmsg: '".$result['errmsg']."' ");
            }

        }else{
            $errormsg = "";
            foreach($check as $v){
                $errormsg.= $v." ";
            }
            $this->_view->assign('ErrorMessage',$errormsg);
            $this->_view->assign("errors", $check);
        }
        
        $this->_view->assign('token',tools_help::getCookie('accese_token'));
    }
    
    
    public function toolsAction(){
        $apiUrl = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=LS35eFjlnNMeAdsNhBx-HifEcG3KRb-c6B2GTncf85XC4--oac0CP1MMxlE3EwSDsRiiOQGql8uXQlhVDPVegqeA-BY7XuT_Aj_8C4trl-MZMUgAEAHUC";
        //echo tools_help::getCookie('access_token');exit;
        $result = $this->weixinCurlGet($apiUrl);
        var_dump($result);
        exit;
    }
    
    private function menuCurl($url,$data){       
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, "'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)'");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $result = curl_exec($ch);
            
        //判读执行过程中是否有错误，有则发送数据错误报告.
        if (curl_errno($ch)) {
          echo 'Error' . curl_error($ch); //用户检查php运行环境中的curl模块开启情况.
        }
        curl_close($ch);
        
        return $result;
    }
    
    
    /**
     * curl get 针对微信类型
     * @param type $url
     * @return type
     */
    private function weixinCurlGet($url){
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_HEADER, 0);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  
        $data = curl_exec($ch);   
        curl_close($ch);
        return $data;
     }
     
    /**
     * curl post 微信类型
     * @param type $url
     * @param type $data
     * @param type $json 转换json格式
     * @return type 返回json类型
     */
    private function weixinCurlPost($url,$data,$json=false){
        if($json){
            $data = json_encode($data);
        }
        //print_r($url);exit;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  
        $result = curl_exec($ch);
        if (curl_errno($ch)) {  
           echo  'curl falied. Error Info: '.curl_error($ch); exit; 
        }  
        curl_close($ch);
        return $result;
    }
    
    /**
     * 设置公众号
     */
    public function setAccountAction(){
    	
    	$model = new AccountModel();
    	
    	$list = $model->select(array('id'=>1));
    	
    	//post数据处理
    	if($this->getRequest()->isPost()){   	
    		
    		$pdata = $this->getAllPost();   		
    		$pdata['appID'] = trim($pdata['appID']);
    		$pdata['appSecret'] = trim($pdata['appSecret']);
    		
    		//查询token
    		$apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$pdata['appID']."&secret=".$pdata['appSecret'];
    		//echo $apiUrl;exit;
    		$result_token = $this->weixinCurlGet($apiUrl);
    		$result_token = json_decode($result_token,true);
    		//var_dump($result_token);exit;

    		//判断token是否有误
    		if(!isset($result_token['access'])){
    			
    			Tools_help::setSession('access_token',array('value'=>$result_token['access'],'updateTime'=>time()));
    			
    			$pdata['id'] = 1;
    			$pdata['updateTime'] = time();
    			//判断是否有插入数据，
    			if(!$list){
    				$result = $model->insert($pdata);
    				$result =true;
    			}else{
    				$result = $model->update('id=1', $pdata);
    			}
   
    			if($result){
    				$this->_view->assign('Message','设置成功！');
    			}else{
    				$this->_view->assign('ErrorMessage','设置失败！');
    			}
    			
    		}else{
    			$this->_view->assign('ErrorMessage','appID或appseret有误！');
    		}
    		
    	}
    	
    	//数据输出
    	if($list){
 	   		$this->_view->assign('list',$list);
    	}
    }
   
}

